import java.util.*;
import java.io.*;

public class MovieManager {
    private List<Movie> movies = new ArrayList<>();
    private static final String MOVIE_FILE = "movies.txt";

    public MovieManager() {
        loadMoviesFromFile();
    }

    // 从文件加载电影数据
    private void loadMoviesFromFile() {
        try (BufferedReader br = new BufferedReader(new FileReader(MOVIE_FILE))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 6) {
                    Movie movie = new Movie(parts[0], parts[1], parts[2], parts[3],
                            Integer.parseInt(parts[4]), Double.parseDouble(parts[5]));
                    movies.add(movie);
                }
            }
        } catch (IOException e) {
            System.out.println("电影数据文件不存在，将创建新文件");
        }
    }

    // 保存电影数据到文件
    private void saveMoviesToFile() {
        try (PrintWriter pw = new PrintWriter(new FileWriter(MOVIE_FILE))) {
            for (Movie movie : movies) {
                pw.println(movie.getName() + "," + movie.getDirector() + "," +
                        movie.getActors() + "," + movie.getDescription() + "," +
                        movie.getDuration() + "," + movie.getRating());
            }
        } catch (IOException e) {
            System.out.println("保存电影数据失败：" + e.getMessage());
        }
    }

    public boolean addMovie(Movie movie) {
        for (Movie m : movies) {
            if (m.getName().equals(movie.getName())) return false;
        }
        movies.add(movie);
        saveMoviesToFile(); // 保存到文件
        return true;
    }

    public boolean removeMovie(String name) {
        Iterator<Movie> it = movies.iterator();
        while (it.hasNext()) {
            Movie m = it.next();
            if (m.getName().equals(name)) {
                it.remove();
                saveMoviesToFile(); // 保存到文件
                return true;
            }
        }
        return false;
    }

    public Movie getMovieByName(String name) {
        for (Movie m : movies) {
            if (m.getName().equals(name)) return m;
        }
        return null;
    }

    public List<Movie> getAllMovies() {
        return movies;
    }

    // 更新电影信息并保存
    public void updateMovie(Movie movie) {
        saveMoviesToFile();
    }
}